import Router from "vue-router";
import Vue from "vue";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// eslint-disable-next-line no-unused-vars
import localCache from "../utils/localstorage";
Vue.use(Router);

const originalPush = Router.prototype.push;
const originalReplace = Router.prototype.replace;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject);
  }
  return originalPush.call(this, location).catch((err) => err);
};

Router.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalReplace.call(this, location, onResolve, onReject);
  }
  return originalReplace.call(this, location).catch((err) => err);
};

const constantRoutes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/login.vue"),
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/home/home.vue"),
    children: [
      {
        path: "satIndex/:id",
        name: "satIndex",
        component: () => import("../components/modalContent/index.vue"),
        children: [
          {
            path: "sensor/:id",
            name: "sensor",
            component: () => import("../components/modalContent/index.vue"),
          },
        ],
      },
      {
        path: "socket/:id",
        name: "socket",
        component: () => import("../components/modalContent/index.vue"),
      },

      {
        path: "station/:id",
        name: "station",
        component: () => import("../components/modalContent/index.vue"),
      },
    ],
  },
];
const asyncRoutes = [
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("../views/NotFound/NotFound.vue"),
  },
];
const routes = [...constantRoutes, ...asyncRoutes];
// console.log(routes, "routes");
const router = new Router({
  routes,
});

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.path !== "/login") {
    //判断是否已经登录保存token;
    // const token = localCache.getCache("token");
    const token = "xingke";
    if (token) {
      next();
    } else {
      next({ path: "/login" });
    }
  } else {
    next();
  }
});
router.afterEach(() => {
  NProgress.done();
});
export default router;
